<template>
  <div>
      <el-container>
          <el-header>
              <el-col :span="16" style="text-align: left; height: 60px; padding-top: 9px">
                  <span class="sys-title">报工系统</span>
              </el-col>
              <el-col :span="4" class="ename-col">
                  欢迎您：<span class="ename-span">{{ename}}</span>
              </el-col>
              <el-col :span="2" style="height: 60px">头像</el-col>
              <el-col :span="2" style="height: 60px; padding-top: 15px; text-align: right">

                  <el-dropdown @command="handleCommand">
                      <span class="el-dropdown-link">
                          <i class="el-icon-setting"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item command="editPwd">修改密码</el-dropdown-item>
                          <el-dropdown-item command="logout">退出</el-dropdown-item>
                      </el-dropdown-menu>
                  </el-dropdown>
              </el-col>

          </el-header>
          <el-container class="el-container">
              <el-aside width="200px" >
                  <!--default-active：默认页面
                      router='true'：开启路由-->
                  <el-menu
                          :default-active="showPage"
                          class="el-menu-vertical-demo"
                          :router="true">
                      <el-menu-item v-for="menu in this.menus" :key="menu.index"  :index="menu.index">
                          <span slot="title" class="menu-title" v-html="menu.menuName"></span>
                      </el-menu-item>
                  </el-menu>
              </el-aside>
              <el-main>
                  <router-view></router-view>
              </el-main>
          </el-container>
      </el-container>
      <el-dialog
          title="修改密码"
          :visible="editPwdFormVisible"
          :before-close="closeDialog"
          width="410px">
          <el-form :model="formData" :rules="rules" ref="formRef">
              <el-form-item label="请输入原密码" :label-width="formLabelWidth" prop="oldPwd">
                  <el-input v-model="formData.oldPwd" autocomplete="off" show-password></el-input>
              </el-form-item>
              <el-form-item label="请输入新密码" :label-width="formLabelWidth" prop="newPwd">
                  <el-input v-model="formData.newPwd" autocomplete="off" show-password></el-input>
              </el-form-item>
              <el-form-item label="请确认新密码" :label-width="formLabelWidth" prop="newPwd2">
                  <el-input v-model="formData.newPwd2" autocomplete="off" show-password></el-input>
              </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="closeDialog">关闭</el-button>
              <el-button type="primary" @click="saveForm">保存</el-button>
          </div>
      </el-dialog>
  </div>
</template>

<script>
export default {
    name: "Home",
    data() {
        //newPwd的自定义验证
        var validatePass = (rule, value, callback) => {
            if(value.length < 6 ) {
                callback(new Error('密码过短'))
            } else if(value.length > 16){
                callback(new Error('密码过长'))
            } else if(value == this.formData.oldPwd){
                callback(new Error('新密码不能与原密码相同'))
            } else {
                if (this.formData.newPwd2 !== '') {
                    //只验证newPwd2
                    this.$refs.formRef.validateField('newPwd2');
                }
                callback();
            }
        };
        //newPwd2的自定义验证
        var validatePass2 = (rule, value, callback) => {
            if (value !== this.formData.newPwd) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            showPage: getMenus()[0].index,
            menus: getMenus(),
            formData: {
                oldPwd: '',
                newPwd: '',
                newPwd2: ''
            },
            editPwdFormVisible: false,
            formLabelWidth: '120px',
            rules: {
                oldPwd: [
                    { required: true, message: '请输入原密码', trigger: 'blur' },
                    { min: 0, max: 20, message: '员工姓名输入过长', trigger: 'blur' }
                ],
                newPwd: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }
                ],
                newPwd2: [
                    { required: true, message: '请确认新密码', trigger: 'blur' },
                    { validator: validatePass2, trigger: 'blur' }
                ],
            },

        }
    },
    methods: {
        //点击设置中的菜单
        handleCommand(command) {
            //修改密码
            if(command == 'editPwd') {
                this.editPwdFormVisible = true
                this.$refs['formRef'].resetFields();
            } else {
                //退出
                //清空session
                sessionStorage.clear()
                //回登录页面
                this.$router.push('/')
            }
        },
        //关闭修改密码的对话框
        closeDialog() {
            this.editPwdFormVisible = false
        },
        //保存修改的密码
        saveForm() {
            const self = this
            //表单验证
            this.$refs['formRef'].validate((valid) => {
                if (valid) {
                    if(self.formData.oldPwd == sessionStorage.getItem('pwd')) {
                        self.$http.post('editPwd',
                            {empno: self.$store.state.emp.empno, pwd: self.formData.newPwd}).then(res => {
                                if(res.data) {
                                    self.$message.success('修改成功')
                                    //更新session中的密码
                                    sessionStorage.setItem('pwd', self.formData.newPwd)
                                    //销毁cookie中保存的密码
                                    self.$cookies.remove('pwd')
                                    //关闭对话框
                                    this.closeDialog()
                                }
                        }).catch(() => {
                                self.$message.error('修改密码失败，请联系管理员')
                        })
                    } else {
                        this.$message.error('原密码错误')
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }

    },
    computed: {
        ename() {
            //重新提交mutation
            let emp = JSON.parse(sessionStorage.getItem("emp"));
            this.$store.commit('setEmp', emp)
            return this.$store.state.emp.ename
        },
    },
    watch:{
        //监听路由的变化
        '$route'(to,from){
            //修改导航菜单的选中
            this.showPage=to.path
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            // 通过 `vm` 访问组件实例
            vm.showPage = to.path
        })
    },
    beforeCreate() {
        //设置body标签的样式
        document.querySelector('body').setAttribute('style', 'margin:0')
    }

}
    //获取侧边栏导航菜单数组
    function getMenus() {
        let job = JSON.parse(sessionStorage.getItem('emp')).job
        let menus = []
        if(job == '1') {
            menus = [
                {index: '/homePage/admin', menuName: '员工管理'},
                {index: '/projectManage', menuName: '项目管理'},
                {index: '/deptManage', menuName: '部门管理'},
            ]
        } else if(job == '2') {
            menus = [
                {index: '/homePage/manager', menuName: '首&nbsp&nbsp&nbsp&nbsp页'},
                {index: '/deptAudit', menuName: '部门审核'},
                {index: '/allReport/manager', menuName: '部门报工'},
                {index: '/allFailReport/manager', menuName: '部门漏报'},
                {index: '/reportPage', menuName: '个人填报'},
                {index: '/allReport/emp', menuName: '个人报工'},
                {index: '/allFailReport/emp', menuName: '个人漏报'},
            ]
        } else {
            menus = [
                {index: '/homePage/emp', menuName: '首&nbsp&nbsp&nbsp&nbsp页'},
                {index: '/reportPage', menuName: '个人填报'},
                {index: '/allReport/emp', menuName: '个人报工'},
                {index: '/allFailReport/emp', menuName: '个人漏报'},
            ]
        }
        return menus
    }
</script>

<style scoped>
.sys-title {
    text-align: left;
    font-size: 30px;
    letter-spacing: 10px;
    color: white;
}
.el-container {
    height: 746px;
    border: 1px solid black;
}
.ename-col {
    height: 60px; color: white; padding-top: 15px; font-size: 20px; letter-spacing: 3px;
}
.ename-span {
    color: white;
    font-weight: bold;
    cursor: pointer;
    text-decoration: underline;
}
.ename-span:hover {
    color: blue;
}
.el-icon-setting {
    color: white;
    font-size: 30px;
    cursor: pointer;
}
.el-icon-setting:hover {
    color: blue;
}
.el-aside {
    border-right: 1px solid darkgray;
 }
.el-header {
    background-color: #545C64;
}
.menu-title {
    letter-spacing: 5px;
    font-weight: bold;
}
</style>